package server

import (
	"fmt"
	"net"

	. "gitee.com/ezios/file-assistant/core"
)

type Connection struct {
	TcpConn net.Conn
}

const DOWNLOAD_PATH = "./download/"

func (c *Connection) work() {
	defer c.TcpConn.Close()

	fmt.Printf("客户[%s]端连接\n", c.TcpConn.RemoteAddr())
	// for {
	buf := make([]byte, 1024)
	n, _ := c.TcpConn.Read(buf)
	message := ParseFromJson(buf[:n])
	if message.Code == MESSAGE_CONN {
		c.TcpConn.Write(buf[:n])
	} else {
		fmt.Println("客户端发送状态异常", message)
		return
	}
	n, _ = c.TcpConn.Read(buf)
	message = ParseFromJson(buf[:n])
	if message.Code != MESSAGE_FILE {
		fmt.Println("客户端发送状态异常|文件信息不完整", message)
		return
	}
	fmt.Printf("文件名称\t文件大小\n%s\t\t%v\n", message.FileInfo.Name, message.FileInfo.Size)
	if message.FileInfo.Size == 0 {
		fmt.Println("文件大小为0")
		return
	}
	//回传响应
	// message.Code = MESSAGE_FILE
	fmt.Println("发送数据：\n", message)
	arr, _ := message.ToJson()
	c.TcpConn.Write(arr)

	//接收文件
	transferFile := TransferFile{
		Path: DOWNLOAD_PATH + message.FileInfo.Name,
		Name: message.FileInfo.Name,
		Size: message.FileInfo.Size,
	}
	transferFile.CreateFile()
	defer transferFile.Close()

	for {
		n, err := c.TcpConn.Read(buf)
		if err != nil {
			if err.Error() != "EOF" {
				fmt.Println("接收文件失败", err)
			} else if err.Error() == "EOF" {
				fmt.Println("接收文件成功")
			}
			return
		}
		transferFile.Write(buf[:n])
	}

	// }
}
